package com.cxb.receiver;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.hardware.input.InputManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Handler;
import android.os.SystemClock;
import android.view.InputDevice;
import android.view.InputEvent;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.widget.Toast;

import com.cxb.BrightnessActivity;
import com.cxb.DeviceInfoActivity;
import com.cxb.GpsTestActivity;
import com.cxb.HistoryListActivity;
import com.cxb.MainActivity;
import com.cxb.R;
import com.cxb.SystemUpdateActivity;
import com.cxb.WeiXinBindActivity;
import com.cxb.WifiAPActivity;
import com.cxb.WifiActivity;
import com.cxb.entity.GpsDestinationInfo;
import com.cxb.manager.NavigationManager;
import com.cxb.manager.RootContext;
import com.cxb.utils.CommonUtils;
import com.cxb.utils.Config;
import com.cxb.utils.SharedPreferencesUtils;
import com.cxb.utils.Tts;

public class SpeechRecognitionReceiver extends BroadcastReceiver {

	private NavigationManager navigationManager;

	@Override
	public void onReceive(final Context context, Intent intent) {

		if (intent.getAction().equals("action.ami.speech_recognition")) {
			String command = intent.getStringExtra("command");

			if ("closeNavi".equals(command)) {
				// 关闭导航
				if (Config.getMapDefault(context) == Config.MAP_AUTOMAP_CAR) {
					closeProcess("com.autonavi.amapauto", context);
				} else if (Config.getMapDefault(context) == Config.MAP_AUTONAVI) {
					closeProcess("com.autonavi.minimap", context);
				}
				if (Config.getMapDefault(context) == Config.MAP_AUTOMAP_LITE) {
					closeProcess("com.autonavi.amapautolite", context);
				}

			} else if ("gotoHome".equals(command)) {
				// 回到HOME
				context.sendBroadcast(new Intent("preview_window_off"));
				int keycode = KeyEvent.KEYCODE_HOME;
				if ("35S".equals(CommonUtils.getInnerVersionName())) {
					keycode = KeyEvent.KEYCODE_F1;
				}

				sendEvent(KeyEvent.ACTION_DOWN, 0, keycode);
				sendEvent(KeyEvent.ACTION_UP, 0, keycode);

			} else if ("showLocation".equals(command)) {
				// 我的位置
				// sendEvent(KeyEvent.ACTION_DOWN, 0);
				if (Config.getMapDefault(context) == Config.MAP_BAIDU) {
					try {
						context.sendBroadcast(new Intent("preview_window_off"));
						Intent baiduIntent = new Intent();
						baiduIntent.setData(Uri.parse("bdnavi://where?src="
								+ context.getPackageName()));
						baiduIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(baiduIntent);
					} catch (Exception e) {
						e.printStackTrace();
					}

				} else if (Config.getMapDefault(context) == Config.MAP_AUTOMAP) {
					context.sendBroadcast(new Intent("preview_window_off"));
					// data=androidamap://myLocation?sourceApplication=softname
					double longitude = intent.getDoubleExtra("longitude", -1);
					double latitude = intent.getDoubleExtra("latitude", -1);
					Intent intent1 = new Intent(
							"android.intent.action.VIEW",
							Uri.parse("androidamap://myLocation?sourceApplication=com.cxb"));
					intent1.setPackage("com.autonavi.minimap");
					intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intent1);
				} else if (Config.getMapDefault(context) == Config.MAP_AUTOMAP_CAR) {

					Intent intent1 = new Intent(
							"android.intent.action.VIEW",
							Uri.parse("androidauto://myLocation?sourceApplication=com.cxb"));
					intent1.setPackage("com.autonavi.amapauto");
					intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent1.addCategory("android.intent.category.DEFAULT");
					context.startActivity(intent1);

				}

			} else if ("closeRecorder".equals(command)) {
				context.sendBroadcast(new Intent("preview_window_off"));
			} else if ("openRecorder".equals(command)) {
				// context.sendBroadcast(new Intent("preview_window_off"));

				intent = new Intent();
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_CLEAR_TASK);
				intent.setClassName("com.cxb.carrecorder",
						"com.cxb.carrecorder.MainActivity");
				context.startActivity(intent);

			} else if ("openNavi".equals(command)) {
				// 打开导航

				if (Config.getMapDefault(context) == Config.MAP_AUTOMAP_CAR) {
					Intent intent1 = new Intent();
					intent1.setAction(Intent.ACTION_MAIN);
					intent1.addCategory(Intent.CATEGORY_LAUNCHER);

					intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
							| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

					intent1.setPackage("com.autonavi.amapauto");
					intent1.setClassName("com.autonavi.amapauto",
							"com.autonavi.auto.remote.fill.UsbFillActivity");
					intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
							| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
					context.startActivity(intent1);
				} else if (Config.getMapDefault(context) == Config.MAP_AUTOMAP_LITE) {
					Intent intent1 = new Intent();
					intent1.setAction(Intent.ACTION_MAIN);
					intent1.addCategory(Intent.CATEGORY_LAUNCHER);

					intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
							| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

					intent1.setPackage("com.autonavi.amapautolite");
					intent1.setClassName("com.autonavi.amapautolite",
							"com.autonavi.auto.remote.fill.UsbFillActivity");
					intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
							| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
					context.startActivity(intent1);
				}
			} else if ("wifiApSetting".equals(command)) {
				// 打开wifi热点设置
				intent = new Intent();
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setClass(context, WifiAPActivity.class);
				context.startActivity(intent);
			} else if ("wifiSetting".equals(command)) {
				// 打开wifi设置
				intent = new Intent();
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setClass(context, WifiActivity.class);
				context.startActivity(intent);
			} else if ("weixin".equals(command)) {
				// 打开微信绑定
				intent = new Intent();
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setClass(context, WeiXinBindActivity.class);
				context.startActivity(intent);
			} else if ("video".equals(command)) {
				// 随手录
				if (CommonUtils.isWeixinBind()) {
					intent = new Intent();
					intent.setClassName("com.cxb.carrecorder",
							"com.cxb.carrecorder.PreviewService");
					intent.setAction("ACTION_GET_VIDEO_SHARE");
					context.startService(intent);
				} else {
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							Tts.showToast(
									context,
									context.getString(R.string.share_fail_because_unbind),
									0);
							Intent intent = new Intent();
							intent.setClass(context, WeiXinBindActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							context.startActivity(intent);

						}
					}, 3000);

				}

			} else if ("capture".equals(command)) {
				// 随手拍
				if (CommonUtils.isWeixinBind()) {
					intent = new Intent();
					intent.setClassName("com.cxb.carrecorder",
							"com.cxb.carrecorder.PreviewService");
					intent.setAction("ACTION_GET_PICTURE_SHARE");
					context.startService(intent);
				} else {
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							Tts.showToast(
									context,
									context.getString(R.string.share_fail_because_unbind),
									0);
							Intent intent = new Intent();
							intent.setClass(context, WeiXinBindActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							context.startActivity(intent);

						}
					}, 3000);
				}

			} else if ("screenOff".equals(command)) {
				// 关闭屏幕

			} else if ("mute_open".equals(command)) {
				// 静音
				setPhoneMute(true, context);
			} else if ("mute_close".equals(command)) {
				// 静音
				setPhoneMute(false, context);
			} else if ("ecard_oneline".equals(command)) {
				if (!Config.isEcardSupport(context)) {
					return;
				}
				Intent tmpIntent = new Intent("com.android.ecar.recv");
				tmpIntent.putExtra("ecarSendKey", "StartECar");
				context.sendBroadcast(tmpIntent);

			} else if ("ecard_onekey_phone".equals(command)) {
				if (!Config.isEcardSupport(context)) {
					return;
				}
				Intent ecardOneKey = new Intent();
				ComponentName componetName = new ComponentName(
						"com.coagent.ecar",
						"com.coagent.ecarnet.car.activity.OneKeyActivity");
				ecardOneKey.setComponent(componetName);
				ecardOneKey.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(ecardOneKey);
			} else if ("ecard_yiyun_phone".equals(command)) {
				if (!Config.isEcardSupport(context)) {
					return;
				}
				Intent yiyunIntent = new Intent();
				ComponentName componetName = new ComponentName(
						"com.coagent.voip",
						"com.coagent.voip.VOIPFragmentActivity");
				yiyunIntent.setComponent(componetName);
				yiyunIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(yiyunIntent);
			} else if ("navigation_history".equals(command)) {
				// 导航历史
				intent = new Intent();
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setClass(context, HistoryListActivity.class);
			} else if ("show_video_list".equals(command)) {
				// 行车记录仪视频列表
				intent = new Intent("action.amitek.video_list");
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
			} else if ("version_info".equals(command)) {
				// 版本信息
				intent = new Intent();
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setClass(context, DeviceInfoActivity.class);
				context.startActivity(intent);
			} else if ("gps_test".equals(command)) {
				// gps测试
				intent = new Intent();
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setClass(context, GpsTestActivity.class);
				context.startActivity(intent);
			} else if ("brightness_setting".equals(command)) {
				// 亮度设置
				intent = new Intent();
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setClass(context, BrightnessActivity.class);
				context.startActivity(intent);
			} else if ("system_update".equals(command)) {
				// 系统升级
				intent = new Intent();
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setClass(context, SystemUpdateActivity.class);
				context.startActivity(intent);
			} else if ("openEdog".equals(command)) {
				Intent electronicEyeintent = new Intent(
						"android.intent.action.MAIN");
				electronicEyeintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				electronicEyeintent.setClassName("com.autonavi.minimap",
						"com.autonavi.map.activity.NewMapActivity");
				electronicEyeintent
						.setData(Uri
								.parse("androidamap://openFeature?featureName=Mine&page=ToolBox&item=ElectronicEye&clearStack=1"));
				context.startActivity(electronicEyeintent);

			} else if ("closeEdog".equals(command)) {
				closeProcess("com.autonavi.minimap", context);
			}

		} else if (intent.getAction().equals("action.ami.restart.unisound")) {
			// 重启云知声服务，为解决云知声概率性初使化失败的问题
			RootContext
					.runCommandForResult("am force-stop com.chemi.framework");
			RootContext
					.runCommandForResult("am force-stop com.unisound.unicar.gui");
			RootContext.runCommandForResult("pm clear com.chemi.framework");
			RootContext
					.runCommandForResult("am startservice -n com.unisound.unicar.gui/com.unisound.unicar.gui.ui.WindowService");
		}

	}

	//
	// public void changePhoneMuteState(boolean isMute) {
	// Intent intent = new Intent("action.ami.speech_recognition");
	// intent.putExtra("event", 6);
	// intent.putExtra("isMute", isMute);//true时表示取消静音，false时表示打开静音模式
	//
	// context.sendBroadcast(intent);
	// }
	// public void showMyLocation(double longitude, double latitude) {
	// Intent intent = new Intent("action.ami.speech_recognition");
	// intent.putExtra("command", "init_ok");
	//
	// context.sendBroadcast(intent);
	// }

	// public void sendNaviInfo(String address, long longitude, long latitude) {
	// Intent intent = new Intent("action.ami.speech_recognition");
	// intent.putExtra("event", 1);
	// intent.putExtra("longitude", longitude);
	// intent.putExtra("latitude", latitude);
	// intent.putExtra("address", address);
	// context.sendBroadcast(intent);
	// }

	void sendEvent(int action, int flags, final int KEYCODE) {
		sendEvent(action, flags, SystemClock.uptimeMillis(), KEYCODE);
	}

	@SuppressLint("NewApi")
	void sendEvent(int action, int flags, long when, final int KEYCODE) {
		long mDownTime = SystemClock.uptimeMillis();

		final int repeatCount = (flags & KeyEvent.FLAG_LONG_PRESS) != 0 ? 1 : 0;
		final KeyEvent ev = new KeyEvent(mDownTime, when, action, KEYCODE,
				repeatCount, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags
						| KeyEvent.FLAG_FROM_SYSTEM
						| KeyEvent.FLAG_VIRTUAL_HARD_KEY,
				InputDevice.SOURCE_KEYBOARD);
		// InputManager im = (InputManager)
		// context.getSystemService(context.INPUT_SERVICE);
		Class inc;
		try {
			inc = Class.forName("android.hardware.input.InputManager");
			Method getInstance = inc.getMethod("getInstance");
			InputManager inputManager = (InputManager) getInstance.invoke(inc);
			Method inject = inc.getMethod("injectInputEvent", InputEvent.class,
					int.class);
			inject.invoke(inputManager, ev, 0);

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void closeProcess(String packageName, Context context) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		try {
			Method forceStopPackage = am.getClass().getDeclaredMethod(
					"forceStopPackage", String.class);
			forceStopPackage.setAccessible(true);
			forceStopPackage.invoke(am, packageName);// com.android.mms是要结束进程的包名
		} catch (SecurityException e) {

		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}

	}

	private void setPhoneMute(boolean enable, Context context) {

		AudioManager audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		SharedPreferencesUtils sp = new SharedPreferencesUtils(context);
		if (enable) {
			int volumn = audioManager
					.getStreamVolume(AudioManager.STREAM_MUSIC);
			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
			audioManager
					.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, 0);
			audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, 0, 0);
			audioManager.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
			audioManager.setStreamVolume(AudioManager.STREAM_ALARM, 0, 0);
			audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
			sp.setVoulmn(volumn);

		} else {
			int volumn = sp.getVolumn();
			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumn, 0);
			audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION,
					volumn, 0);
			audioManager.setStreamVolume(AudioManager.STREAM_ALARM, volumn, 0);
			audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, volumn, 0);
			audioManager.setStreamVolume(AudioManager.STREAM_RING, volumn, 0);
			audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
		}
	}

}
